import { Module } from 'vuex'

import { ILoginState } from './types'
import { IRootState } from '../types'
import {
  accountLoginAction,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '@/serivce/login/login'
import { IAccount } from '@/serivce/login/type'
import router from '@/router'

import locaCache from '@/utils/cache'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
    }
  },
  actions: {
    async accountLoginAction({ commit }, paylaod: IAccount) {
      //实现登陆逻辑
      const loginResult = await accountLoginAction(paylaod)
      const { id, token } = loginResult.data
      commit('changeToken', token)
      locaCache.setCache('token', token)

      //2.请求用户菜单
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      locaCache.setCache('userInfo', userInfo)

      //3.请求用户权限菜单
      const userMenuResult = await requestUserMenusByRoleId(userInfo.role?.id)
      const userMenus = userMenuResult.data
      commit('changeUserMenus', userMenus)
      locaCache.setCache('userMenus', userMenus)

      //跳转到首页
      router.push('/main')
    },
    loadLocalLogin({ commit }) {
      const token = locaCache.getCache('token')
      if (token) {
        commit('changeToken', token)
      }
      const userInfo = locaCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = locaCache.getCache('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    },
    phoneLoginAction({ commit }, paylaod: any) {
      console.log('执行phoneLoginAction')
    }
  }
}

export default loginModule
